<?php
namespace Home\Controller;
use Think\Controller;

class WxController extends HomeController { 
	  private $token='zb';
	  // public  $echostr = $_GET["echostr"];
      private $appid = 'wx9569e2eacd86156e';
      private $appsecret = '5f682bd2a413bddf6c0c9320168372ad';
      public function index(){
         $res = $this->checkSignature(); 
         if ($res && isset($_GET["echostr"])) {
         	echo  $_GET["echostr"];//自定义回复
         }else{
         	$this->response();//被动回复
         }
     }
      

     private function checkSignature(){
     	$signature =$_GET["signature"];
     	$timestamp =$_GET["timestamp"];
     	$nonce =$_GET["nonce"];
     	$tmpArr = array($this->token,$timestamp,$nonce);
     	sort($tmpArr,SORT_STRING);
     	$tmpArr =sha1(implode($tmpArr));
     	if($tmpArr == $signature ){
     		return true;
     	}else{
     		return false;
     	}
     }

     private function response(){
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $obj = simplexml_load_string($xml);
        if ($obj->MsgType == 'event') {
            if ($obj->Event == 'subscribe') {
                $content ="欢迎关注我@周博！";
                $this->pushtext($obj,$content);
            }elseif($obj->Event == 'CLICK'){
                 switch ($obj->EventKey) {
                   case 'key1':
                   $content = $this->joke();
                   $this->pushtext($obj,$content);
                   break;
            }
        }elseif($obj->Event == 'SCAN'){
        	switch ($obj->EventKey) {
                   case '123':
                   $content = $this->joke();
                   $this->pushtext($obj,$content);
                   break;
                   case '321':
                   $content = $this->joke();
                   $this->pushtext($obj,$content);
                   break;
        }
    }}
        elseif ($obj->MsgType == 'text'){
               switch ($obj->Content) {
                   case '1':
                        $arr = array(
                        array('Title' => '百度', 
                          'Description' => '百度一下',
                           'PicUrl' => 'https://www.baidu.com/img/bd_logo1.png', 
                           'Url' => 'https://www.baidu.com/'),
                        array('Title' => '网易', 
                          'Description' => '网易首页', 
                          'PicUrl' => 'https://ss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=2490895003,2642262494&fm=58&s=2370E532CFA568134854D6FC0300F020',
                         'Url' => 'http://www.163.com/'),
                    );
                       $this->pushtextpic($obj,$arr);
                       break;
                   case '2':
                        $content = $this->getAccessToken();
                        $this->pushtext($obj,$content);
                       break;
                   case '3':
                        $content = $this->qrtmp();
                       $arr = array(
                        array('Title' => '二维码', 
                          'Description' => '二维码321',
                           'PicUrl' => "$content", 
                           'Url' => "$content")
                    );
                        $this->pushtextpic($obj,$arr);
                       break;
                    default:
                        if(mb_substr($obj->Content,-2) == '天气'){
                            $res = $this->weather(mb_substr($obj->Content,0,-2));
                            $this->template($obj->FromUserName,$res);
                        }elseif(is_numeric(mb_substr($obj->Content,-3))){
                            $res = $this->transit(mb_substr($obj->Content,0,-3),mb_substr($obj->Content,-3));
                            $this->template2($obj->FromUserName,$res,mb_substr($obj->Content,0,-3),mb_substr($obj->Content,-3));
                        }
                        else{
                            $content = $this->robot($obj->Content,substr($obj->FromUserName,-5));
                            $this->pushtext($obj,$content);
                        }
                        break;
                       }
            }
    }
    //上传图片回复图片
    private function pushpic($obj,$content){
        $str = '<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%d</CreateTime>
                <MsgType><![CDATA[%s]]></MsgType>
                <Image>
                <MediaId><![CDATA[%s]]></MediaId>
                </Image>
                </xml>';
                echo sprintf($str, $obj->FromUserName, $obj->ToUserName, time(),'image', $content);
    }

    private function pushtext($obj,$content){
        $str = '<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%d</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    </xml>';
                // $content ="你的消息是1";
                echo sprintf($str, $obj->FromUserName, $obj->ToUserName, time(),'text', $content);
    }

    private function pushtextpic($obj,$arr){
        $str = '<xml>
                <ToUserName><![CDATA[' . $obj->FromUserName . ']]></ToUserName>
                <FromUserName><![CDATA[' . $obj->ToUserName . ']]></FromUserName>
                <CreateTime>' . time() . '</CreateTime>
                <MsgType><![CDATA[news]]></MsgType>
                <ArticleCount>' . count($arr) . '</ArticleCount>
                <Articles>';
        foreach ($arr as $val){
            $str .= '<item>
                <Title><![CDATA[' . $val['Title'] . ']]></Title>
                <Description><![CDATA[' . $val['Description'] . ']]></Description>
                <PicUrl><![CDATA[' . $val['PicUrl'] . ']]></PicUrl>
                <Url><![CDATA[' . $val['Url'] . ']]></Url>
                </item>';
        }
        $str .= '</Articles>
                </xml>';
        echo $str;
    }

    private function getAccessToken(){
        $url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
        if (S('accessToken') == null) {
           $a = $this->curlSub($url);
           S('accessToken',$a['access_token'],7200);
      }
       return S('accessToken');
   }

   //file_put_contents方法（与curl不能同时使用）
//    private function getaccesstoken() {
//         $res = file_get_contents("accesstoken.dat");
//         $dat = unserialize($res);
//         if (empty($res) || $dat['time'] < time()) {
//             $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appID}&secret={$this->appsecret}";
//             $res = $this->curlSub($url);
//             $dat['time'] = time() + $res['expires_in'] - 200;
//             $dat['time'] = time() + 10;
//             $dat['access_token'] = $res['access_token'];
//             file_put_contents("accesstoken.dat", serialize($dat));
//         }
//         return $dat['access_token'];
//     }
    
   //curl方法
   private function curlSub($url,$post=null){
    // var_dump($url,$post);
        //1.初始化
    $ch = curl_init();

        //2.相关设置
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    if (stripos($url, "https://") !== false) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }
     // var_dump($post);
    if($post != null){
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }
        //3.执行
    $res = curl_exec($ch);

        //当遇到错误的时候，我们可以将curl的错误打印出来
    if(curl_errno($ch) != 0){
        var_dump("错误号是".curl_errno($ch)."错误原因".curl_error($ch));
    }
        //4.关闭
    curl_close($ch);
    // var_dump(json_decode($res,true));
    return json_decode($res,true);
}

/**
     * 微信api不支持中文转义的json结构
     * @param array $arr
     */
    public static function json_encode($arr) {
        $parts = array();
        $is_list = false;
        //Find out if the given array is a numerical array
        $keys = array_keys($arr);
        $max_length = count($arr) - 1;
        if (($keys[0] === 0) && ($keys[$max_length] === $max_length)) {
            //See if the first key is 0 and last key is length - 1
            $is_list = true;
            for ($i = 0; $i < count($keys); $i++) {
                //See if each key correspondes to its position
                if ($i != $keys[$i]) {
                    //A key fails at position check.
                    $is_list = false; //It is an associative array.
                    break;
                }
            }
        }
        foreach ($arr as $key => $value) {
            if (is_array($value)) {
                //Custom handling for arrays
                if ($is_list) {
                    $parts[] = self::json_encode($value);
                }
                /* :RECURSION: */ else {
                    $parts[] = '"' . $key . '":' . self::json_encode($value);
                }
                /* :RECURSION: */
            } else {
                $str = '';
                if (!$is_list) {
                    $str = '"' . $key . '":';
                }

                //Custom handling for multiple data types
                if (is_numeric($value) && $value < 2000000000) {
                    $str .= $value;
                }
                //Numbers
                elseif ($value === false) {
                    $str .= 'false';
                }
                //The booleans
                elseif ($value === true) {
                    $str .= 'true';
                } else {
                    $str .= '"' . addslashes($value) . '"';
                }
                //All other things
                // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
                $parts[] = $str;
            }
        }
        $json = implode(',', $parts);
        if ($is_list) {
            return '[' . $json . ']';
        }
        //Return numerical JSON
        return '{' . $json . '}'; //Return associative JSON
    }
 //删除自定义菜单
    public function delMenu(){
        $url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token={$this->getAccessToken()}";
        $res = $this->curlSub($url);
    }
 //自定义菜单
    public function customMenu(){
        $url ="https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$this->getAccessToken()}";
        $data = [
            'button'=>[
                [
                    'type'=>'click',
                    'name'=>'每日一笑',
                    'key'=>'key1',
                ],
                [
                    'name'=>'菜单',
                    'sub_button'=>[
                        [
                            'type'=>'view',
                            'name'=>'百度一下',
                            'url'=>'http://www.baidu.com/',
                        ],
                        [
                            'type'=>'pic_photo_or_album',
                            'name'=>'微信相册发图',
                            'key'=>'k2',
                            'sub_button'=>[],
                        ],
                        [
                            'type'=>'location_select',
                            'name'=>'发送位置',
                            'key'=>'k3',
                        ],
                    ]
                ],
            ],
        ];
     
    $res = $this->curlSub($url,$this->json_encode($data));
    var_dump($this->json_encode($data));
    echo '<hr>';
    var_dump($res);
}

        public function robot($info,$userid){
            $url ="http://op.juhe.cn/robot/index?info={$info}&key=18c7dcaa501f00a193443e0d0bad3b31&userid={$userid}";
            $res = $this->curlSub($url);
            if ($res['result']['code'] == 100000){
                return $res['result']['text'];
            }else{
                die('机器人开小差了');
            }
            
        }

   

        public function joke(){
           $key ="6cbc9fd857885d254c5c92a7ae5a5daa";
           $max =3600*24*30*24;
           $time= time()-mt_rand(0,$max);
           $url = "http://japi.juhe.cn/joke/content/list.from?key={$key}&sort=desc&time={$time}";
                $res = $this->curlSub($url);
                if ($res['reason']=='Success') {
                   return $res['result']['data']['0']['content'];
                }else{
                    die('错误号:');
                }
        }

        public function weather($city=null){
           $city=urlencode($city);
           $key ="29bad091bfb04e2c36ff73723e49f56d";
           $url = "http://v.juhe.cn/weather/index?format=1&cityname={$city}&key={$key}";
                $res = $this->curlSub($url);
                if ($res['resultcode']==200) {
                     return ($res['result']);
                }else{
                    die('能力有限');
                }
        }

        public function template($userid,$res){
            // $res = $this->weather($city="武汉");
            $url ="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$this->getAccessToken()}";
            $data = [
           "touser"=>$userid,
           "template_id"=>"jCOFuxNJgxGtae3yUO5I3d7Y1kxh72qcbNKTI3rl5ms",
           "url"=>"http://www.weather.com.cn",  
           'data'=>[
                'city'=>[
                    'value'=>$res['today']['city'],
                    'color'=>'#000',
                ],

                'temp'=>[
                    'value'=>$res['today']['temperature'],
                    'color'=>'#000',
                ],

                'wind_direction'=>[
                    'value'=>$res['sk']['wind_direction'],
                    'color'=>'#000',
                ],

                'weather'=>[
                    'value'=>$res['today']['weather'],
                    'color'=>'#000',
                ],

                'dressing_advice'=>[
                    'value'=>$res['today']['dressing_advice'],
                    'color'=>'#000',
                ],

            ],
       ];   
             $this->curlSub($url,$this->json_encode($data));
        }


        public function transit($city =null,$num=null) {
            // $city = '武汉';
            // $num = '510';
            $key = '35cdbd74d7731d9c8ad8f952fe2c4f2d';
            $url = "http://op.juhe.cn/189/bus/busline?key={$key}&city={$city}&bus={$num}";
            $res = $this->curlSub($url);
            if ($res['error_code'] == 0) {
                $stationdes = '';
                foreach ($res['result'][0]['stationdes'] as $val) {
                    $stationdes.=$val['name'] . '--->';
                }
                $res['result'][0]['stationdes'] = rtrim($stationdes, '--->');
                return $res['result'][0];
            } else {
            // $this->textpush($obj, '服务器开小差了！');
             die('服务器开小差了！');
         }
     }


        public function template2($userid=null,$res,$city,$num){
            // $res =$this->transit();
            $url ="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$this->getAccessToken()}";
            $data = [
           "touser"=>$userid,
           "template_id"=>"O91NHyDOt_gLLFVmW7uhagipo7ZvpD0OoNQPZlAzHWE",
           "url"=>'https://www.baidu.com/s?wd='.$city.$num, 
           'data'=>[
                'keyname'=>[
                    'value'=>$res['key_name'],
                    'color'=>'#173177',
                ],
                'lineid'=>[
                    'value'=>$res['line_id'],
                    'color'=>'#173177',
                ],
                'frontname'=>[
                    'value'=>$res['front_name'],
                    'color'=>'#173177',
                ],
                'terminal_name'=>[
                    'value'=>$res['terminal_name'],
                    'color'=>'#173177',
                ],
                'company'=>[
                    'value'=>$res['company'],
                    'color'=>'#173177',
                ],
                'stationdes'=>[
                    'value'=>$res['stationdes'],
                    'color'=>'#173177',
                ],
                ],
           ];
             $this->curlSub($url,$this->json_encode($data));
        }
        //临时二维码生成
        public function qrtmp(){
        	$url="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$this->getAccessToken()}";
        	$post ='{"expire_seconds": 604800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 123}}}';
        	$res = $this->curlSub($url,$post);
        	$url2= 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$res['ticket'];
            return $url2;
        }
       //永久二维码生成
        public function qrstr(){
        	$url="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$this->getAccessToken()}";
        	$post ='{"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": "321"}}}';
        	$res = $this->curlSub($url,$post);
        	$url2= 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$res['ticket'];
            $tu ="<img src='{$url2}'>";
            echo $tu;
        }

}

?>